#!/bin/bash

. $OPENARS_HOME/common/debug.h
. $OPENARS_HOME/common/functions.h

repository="$REPOSITORY_PATH/scripts"
if [ ! -d "$repository" ]; then
    ERR "not find repository dir"
    exit 1
fi

>$OUTFILE
list=`ls -a $repository | grep -v ".svn" | grep -v "^\.*$"`
INF "Check `echo "$list" | awk 'END{print NR}'` scripts. "
CMDB=`echo $CONNECT_CMDB | awk -F"/" '{print $1}'`


for script_name in $list
do
echo $script_name
RES=`$ORACLE_HOME/bin/sqlplus -s /NOLOG  <<END
set $SQL_PARAM
set linesize 100
connect $CONNECT_ZABBIX
select h2.host from hosts_templates t,hosts h1, hosts h2, $CMDB.hosts c where \
t.templateid=h1.hostid and t.hostid=h2.hostid and h1.host in \
(select template_name  from template_scripts where script_name like '%/$script_name%') \
and h2.host=c.host and c.control='YES' and h2.available=1;
exit;
END`
if [ $? -ne 0 ]; then
    ERR "sqlplus ERROR: $RES"
    exit 1
fi
[ -z "$RES" ] && { WARN "not find servers for $script_name"; continue; }

pt=`$ORACLE_HOME/bin/sqlplus -s /NOLOG  <<END
set $SQL_PARAM
set linesize 100
connect $CONNECT_ZABBIX
select script_name from template_scripts where script_name like '%/$script_name%';
exit;
END` 
if [ $? -ne 0 ]; then
    ERR "sqlplus ERROR: $pt"
    exit 1
fi

pt=`echo $pt |sed s/'.*,'// |sed s/\$.//g | sed s/\ *$//`
cksum_loc=`/usr/bin/cksum $repository/$script_name |awk '{print $1}'`

#INF "check $script_name on servers: `echo $RES`"

for server in $RES
do
(
SSH $USER_ZABBIX@$server "/usr/bin/cksum $pt | awk '{print \$1}'" result
[ "$?" -ne 0 ] && continue
[ "$result" != "$cksum_loc" ] && ERR "Error $script_name cksumm in repository or $server!"
) &
done

done 
wait

exit 0;
